#include "button.h"
#include "eventServer.h"

Button::Button(std::string _type, std::string _name, Object* _object) :
    GuiElement(_type,_name,_object) {
}

void Button::run() {
    GuiElement::run();
    
    updateText(object->getVar("text",Var(std::string(""))));
    object->subscribeSetVar("text",boost::bind(&Button::updateText,this,_1));
}

CEGUI::Window* Button::makeWindow(CEGUI::WindowManager* windowManager) {
    CEGUI::PushButton* button = (CEGUI::PushButton*)windowManager->createWindow("TaharezLook/Button",object->name);
    button->subscribeEvent(CEGUI::PushButton::EventClicked,
        CEGUI::Event::Subscriber(&Button::onClick,this));
    return button;
}

void Button::updateText(Var val) {
    if (window && boost::any_cast<std::string>(&val)) {
        std::string text = boost::any_cast<std::string>(val);
        window->setText(text);
    }
}

bool Button::onClick(const CEGUI::EventArgs& evt) {
    VarMap args;
    args["sender"] = object->name;
    EventServer::getSingleton().publish("buttonClicked",args);
}
